package com.example.security.aspect;

import com.example.security.annotation.RequirePermissions;
import com.example.security.entity.SysUser;

import com.example.security.exception.BusinessException;
import com.example.security.service.SecurityService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class PermissionCheckAspect {

    private final SecurityService securityService;

    @Around("@annotation(requirePermissions)")
    public Object checkPermissions(ProceedingJoinPoint point, RequirePermissions requirePermissions) throws Throwable {
        SysUser user = securityService.getCurrentUser();
        String[] permissions = requirePermissions.value();
        com.example.security.enums.Logical logical = requirePermissions.logical();
        
        if (!hasPermissions(user.getId(), permissions, logical)) {
            throw new BusinessException("您没有操作权限");
        }
        
        return point.proceed();
    }
    
    /**
     * 判断用户是否具有权限
     */
    private boolean hasPermissions(Long userId, String[] permissions, com.example.security.enums.Logical logical) {
        // 系统管理员拥有所有权限
        if (securityService.isAdminById(userId)) {
            return true;
        }
        
        // 获取用户权限列表
        boolean hasPermission = false;
        if (com.example.security.enums.Logical.OR.equals(logical)) {
            hasPermission = Arrays.stream(permissions)
                .anyMatch(permission -> securityService.hasPermission(userId, permission));
        } else {
            hasPermission = Arrays.stream(permissions)
                .allMatch(permission -> securityService.hasPermission(userId, permission));
        }
        
        return hasPermission;
    }
} 